package com.cellngine.hub;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import com.cellngine.Constants;
import com.cellngine.Cellngine;

public class WebServerThread implements Runnable
{
	private WebServer		master;
	private ServerSocket	server;
	
	public WebServerThread(final WebServer master, final ServerSocket server)
	{
		this.master = master;
		this.server = server;
	}
	
	@Override
	public void run()
	{
		while (this.master.isRunning())
		{
			try
			{
				//Start accepting connections; when one is received create a new thread to handle it.
				final Socket s = this.server.accept();
				
				final Thread t = new Thread(new WebServerHandler(s));
				t.start();
			}
			catch (final SocketException e)
			{
				//The server has been shut down, so we don't need to report anything.
				return;
			}
			catch (final IOException e)
			{
				Cellngine.log(e, Constants.log_type.error);
			}
			
			//Make sure other threads (i.e., client processing threads and the main thread) can still function.
			Thread.yield();
		}
	}
	
	public void close()
	{
		try
		{
			this.server.close();
		}
		catch (final IOException e)
		{
			Cellngine.log(e, Constants.log_type.error);
		}
	}
}